import axios from 'axios';
import { RSAEncrypt } from "./JSEncrypt.js";
// import Encrypt from './JSEncrypt.js';
// 自定义错误类
class BaseErr extends Error {
  constructor(message) {
    super(message);
    this.name = 'BaseErr';
  }
}

// RSA加密工具（实际项目中建议使用成熟库如jsencrypt）
class RSAEncryptor {
  // 模拟RSA加密，实际使用时需替换为真实公钥和加密逻辑
  static encrypt(text) {
    // 这里仅做简单演示，真实场景需使用实际RSA算法
    return btoa(encodeURIComponent(text));
  }
}

// 登录处理器类
class UnicomLoginHandler {
  constructor(options = {}) {
    this.mobile = options.mobile || '';
    this.smscode = options.smscode || '';
    this.appId = options.appId || '';
    this.appName = options.appName || '中国联通';
    this.cookie = '';
    // 初始化本地存储
    this.initStore();
  }

  // 初始化本地存储
  initStore() {
    if (typeof window !== 'undefined') {
      const storedCookie = localStorage.getItem('unicom_cookie');
      const storedAppId = localStorage.getItem('unicom_appId');
      if (storedCookie) this.cookie = storedCookie;
      if (storedAppId) this.appId = storedAppId;
    }
  }

  // 日志输出
  log(message) {
    console.log(`[${new Date().toISOString()}] ${message}`);
  }

  // 消息提示
  msg(title, content, type = 'info') {
    console.log(`[${title}] ${content}`);
    // 实际项目中可替换为UI组件的消息提示
  }

  // 转换参数为form-urlencoded格式
  transParams(params) {
    return Object.entries(params)
      .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
      .join('&');
  }


  // 存储数据到本地
  setStore(key, value, persistent = false) {
    this[key] = value;
    if (persistent && typeof window !== 'undefined') {
      localStorage.setItem(`unicom_${key}`, value);
    }
  }

  // 发送POST请求
  async post({ url, body, headers = {} }) {
    try {
      const response = await axios({
        method: 'post',
        url,
        data: body,
        headers: {
          'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
          'Referer': 'https://m.client.10010.com/',
          ...headers
        },
        withCredentials: true,
        responseType: 'text'
      });

      return {
        body: response.data,
        headers: response.headers
      };
    } catch (error) {
      this.log(`请求失败: ${error.message}`);
      throw new BaseErr(`网络请求异常: ${error.message}`);
    }
  }

  // 验证码登录处理
  async handleLoginAction() {
    this.log('运行 》 中国联通验证码登录');

    if (!this.mobile || !this.smscode) {
      throw new BaseErr('⚠️ 请配置 手机号(mobile), 验证码(smscode)');
    }

    this.log('〽️ 开始尝试验证码方式登录');
    
    try {
      let vo = await this.post({
        url: 'https://m.client.10010.com/mobileService/radomLogin.htm',
        body: this.transParams({
          mobile: RSAEncrypt(this.mobile),
          password: RSAEncrypt(this.smscode),
          appId: this.appId,
          version: 'iphone_c@9.0100',
        }),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      });

      this.log('↓ 响应内容');
      this.log(vo.body);
    //   vo.headers

      let res;
      try {
        res = JSON.parse(vo.body);
      } catch (e) {
        throw new BaseErr("验证码方式登录失败，JSON数据解析异常");
      }

      if (res.success === '0') {
        const headers = vo.headers;
        let cookie = headers['set-cookie'] || headers['Set-Cookie'];
        
        if (Array.isArray(cookie)) {
          cookie = cookie.join('; ');
        }
        
        this.log(`验证码方式登录 Cookie`);
        
        if (!cookie) {
          throw new BaseErr(`获取到的验证码方式登录 Cookie 为空！`);
        }
        
        this.cookie = cookie;
        this.log('cookie:\n' + cookie);
        this.setStore('cookie', cookie, true);
        
        if (res.appId) {
          this.setStore('appId', res.appId, true);
          this.log('appId:\n' + res.appId);
        }
        
        this.msg(this.appName, '🍪 验证码方式登录成功！', 'success');
        return {
          success: true,
          message: '验证码方式登录成功！',
          data: { cookie, appId: res.appId }
        };
      } else {
        let desc = res.dsc || '未知错误';
        throw new BaseErr(`验证码方式登录失败！${desc}`);
      }
    } catch (error) {
      this.log(`登录过程出错: ${error.message}`);
      throw error;
    }
  }

   async query() {
          this.log('--- 开始尝试查询流量');
          var cookie = this.cookie;
          let vo = await this.post({
              url: 'https://m.client.10010.com/servicequerybusiness/operationservice/queryOcsPackageFlowLeftContentRevisedInJune',
              headers: { cookie },
          })
          let body = vo.body;
  
          let res;
          try {
              res = JSON.parse(body);
              console.log(vo)
          } catch (e) {
              throw new BaseErr("查询流量失败！JSON数据解析异常");
          }
  
          console.log('↓ res body')
          console.log(JSON.stringify(res))
  
  
          if (vo.status == 200 && res.code === '0000') {
              this.log('🍪查询流量成功！');
              return res;
          } else {
              const desc = res.desc;
              let errMsg = '查询流量失败！未知错误';
              if (String(body) === '999999' || String(body) === '999998') {
                  return false;
              } else if (res.code === '4114030182') {
                  errMsg = '"查询流量失败！系统升级';
              } else if (desc) {
                  errMsg = "查询流量失败！" + desc;
              }
              throw new BaseErr(errMsg);
          }
      }
}


const ck='acw_tc=1a0c63a217562660807552827e581fca07f3e379e07182781f16669e6b42e9;path=/;HttpOnly;Max-Age=1800; c_id=7f767a5d7775cd5dbd5b67f0a5672c923b766e404db87517fe1de50ac0a35930; Domain=.10010.com; Path=/; u_type=11; login_type=06; Domain=.10010.com; Path=/; u_account=15598182031; Domain=.10010.com; Path=/; city=010|101|91296262|-99; Domain=.10010.com; Path=/; c_version=iphone_c@9.0100; Domain=.10010.com; Path=/; enc_acc=brJ6OGweow4TuiDTDxlnir8HtLs/eh6zeUCDYtqS7Mn4LZkmOYbnrJEPE2S8sZpK8rQOo+obHPsQMZ3H26r2cuWzLUBv1AB/cq9XvqzpAs3ZRKMwwlACnNURcGhdZErJexCAiAnDCNGcS4NfTUWwUNgKMAMPv4qZu3yZqW1pXy4=; Domain=.10010.com; Path=/; ecs_acc=brJ6OGweow4TuiDTDxlnir8HtLs/eh6zeUCDYtqS7Mn4LZkmOYbnrJEPE2S8sZpK8rQOo+obHPsQMZ3H26r2cuWzLUBv1AB/cq9XvqzpAs3ZRKMwwlACnNURcGhdZErJexCAiAnDCNGcS4NfTUWwUNgKMAMPv4qZu3yZqW1pXy4=; Domain=.10010.com; Path=/; random_login=1; Domain=.10010.com; Path=/; cw_mutual=7064d003eb3c8934e769e430ecf3d64a67e1af14c007b48658619c33149222744895fdb432977f6a68bd1bceaaa2c5c12040157910ad09b77137d3bf198342a2; Domain=.10010.com; Path=/; t3_token=97d2135c6ab167e7f89f8d0fc720c8d0; Domain=.10010.com; Path=/; invalid_at=7faca970637d41aef30feac99b647cab7073ff0e1b5af841e93f8667c0a5f657; Domain=.10010.com; Path=/; c_mobile=15598182031; Domain=.10010.com; Path=/; wo_family=0; Domain=.10010.com; Path=/; u_areaCode=; Domain=.10010.com; Path=/; third_token=eyJ2ZXJzaW9uIjoiMDAiLCJkYXRhIjoiZjQ5NTUyNTEyZDExZGY4ZTQ1Yjg2MTlkMDc5Y2Y4NTUxNjIxYjU2MDY4YmFmNWJmMTU5N2M4NjkzMmE5YWNlOWM4N2I2M2YxYzFmZjY3ZjEwMjM0ODhjNDY4YjRmMzZlMzZkODAxMzlmZTVhMDFhNzA1ZDI1YWQzZmJhODM5MjU1OWM1NmVhYTliMWQ3MDA2YmMyZmYzOGI1NDQ5NGJiMyJ9; Domain=.10010.com; Path=/; ecs_token=eyJ2ZXJzaW9uIjoiMDAiLCJkYXRhIjoiNTIzNmU3YzQwYTAyYjBkZTQ4YmZiMTdkZWJmOTM3ZGI5YmI0ODFlNTA2ZTY2N2YyMWQ3MmIxZGNmYTBlNWZlN2IxNDc2MDM2ZWM2MDE2MmFiZTJmYjJjNDUwZmIxNmY0ZTMwMWM5ZDhjYmE4OWZhMzlkNjVkMTQ1YTQ0MmM5OGM3OWMyODNkY2I1MzBjNzdjODg3NzFkZjBjMWRlZjJmYjMzMGY3YTA0YjkwZGU3OTZkYjI1MGU1MzY5NzJiNjJlMjY2YjQwNzg2ODM1NzJkYWI2MmNjZGJlZWU3NDQzYWQ0NTBjMzQ1MjdmZWI3MzdlNTdkMjA3ODAxZTBmNjE2ZTc4OTY1OTdiMmZmMDZjY2M5NTQwODY5OTBkYmRlZmVkZTIwYzdhNWRkMTI4NDY0MTVjY2ZiNGI4YWRjYzNmOGIifQ==; Domain=10010.com; Path=/; c_sfbm=234g_00;path=/';
// 使用示例
const loginHandler = new UnicomLoginHandler({
  mobile: '15598182031',
  smscode: '1428885909@Lt',
//   cookie:ck,
  appId:'06eccb0b7c2fd02bc1bb5e8a9ca287413eae2a7e8dbe254f3b0e117d20ecac11eff71279be5ac47597693683421a0ff76a1707cacc5ed0460d5535c2de563a9c5576473023692a43c09f9ecd8b30bff1'
});

try {
  const result = await loginHandler.handleLoginAction();
  const result1 = await loginHandler.query();
  console.log('登录结果:', result);
  console.log('查询结果:', result1);
} catch (err) {
  console.error('登录失败:', err.message);
}
